
import { ecs } from "../framework/assets/libs/ecs/ECS";
import { InitComponent } from "./initComponent";
import { AsyncQueue, NextFunction } from "../framework/assets/libs/collection/AsyncQueue";
import { resLoader } from "../framework/assets/core/common/loader/ResLoader";
import { oops } from "../framework/assets/core/Oops";
import { UIPrefabType } from "../config/config";
import { LoadingComp } from "./loadingComp";


// 游戏初始化系统

export class InitSystem extends ecs.ComblockSystem implements ecs.IEntityEnterSystem {
    filter(): ecs.IMatcher {
        return ecs.allOf(InitComponent);
    }

    // 进入 loading 时加载资源
    entityEnter(entity: ecs.Entity) {
        const queue: AsyncQueue = new AsyncQueue();
        // 多语言
        this.loadLanguage(queue);
        this.loadCommon(queue);
        // 初始完成
        this.initComplete(queue, entity);
        queue.play();
    }

    // 语言包
    private loadLanguage(q: AsyncQueue) {

    }

    // 公共资源
    private loadCommon(q: AsyncQueue) {
        // 执行成功时调用 next
        q.push((next: NextFunction, params: any, args: any) => {
            resLoader.loadDir('common', next)
        })
    }

    private initComplete(q: AsyncQueue, entity: ecs.Entity) {
        // 所有资源加载完成以后，再打开 loading 页
        q.complete = async() => {
            const node = await oops.gui.openAsync(UIPrefabType.loading);
            // 添加 loading 页(所有资源, 数据都加载好了,加载剩下的loading 页)
            // loading 页不需要 system 按帧更新
            if (node) {
                entity.add(node.getComponent(LoadingComp));
            }
            // 删除初始化组件
            entity.remove(InitComponent)
        };
    }
}
